package com.icare.common.service.autoconfig;

import com.icare.common.service.utils.StringUtils;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Parameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * swagger自动配置
 *
 * @author TianHaibo
 * @create 2018-04-04 17:13
 **/
@Configuration
@EnableSwagger2
@ConditionalOnProperty({"swagger.conf.host"})
@ConfigurationProperties("swagger.conf")
@Data
@Slf4j
public class SwaggerAutoConfig {
    private String groupName;
    private String basePackage;
    private String title;
    private String host;
    private String desc;
    private String serviceUrl;
    private String version = "1.0.0";

    @Value("${spring.application.name:null}")
    private String appName;

    @Bean
    public Docket createRestApi() {
        log.info("初始化swagger");
        if(StringUtils.isEmpty(groupName)){
            groupName = appName;
        }
        List<Parameter> pars = new ArrayList<Parameter>() {
            private static final long serialVersionUID = 1L;

            {
                this.add((new ParameterBuilder()).name("token").description("全局会话Token").modelRef(new ModelRef("string")).parameterType("header").required(false).build());
            }
        };
        return (new Docket(DocumentationType.SWAGGER_2)).groupName(this.groupName).apiInfo(this.apiInfo()).host(this.host).select().apis(RequestHandlerSelectors.basePackage(this.basePackage)).paths(PathSelectors.any()).build().globalOperationParameters(pars);
    }

    private ApiInfo apiInfo() {
        if(StringUtils.isEmpty(serviceUrl)){
            serviceUrl = "http://"+host+"/";
        }
        if(StringUtils.isEmpty(desc)){
            desc = "api路径http://"+host+"/";
        }
        if(StringUtils.isEmpty(title)){
            title = appName;
        }
        return (new ApiInfoBuilder()).title(this.title).description(this.desc).termsOfServiceUrl(this.serviceUrl).version(this.version + LocalDateTime.now()).build();
    }

}
